from django.shortcuts import render

# Create your views here.
from rest_framework import status, mixins, serializers
from rest_framework.decorators import action
from rest_framework.generics import GenericAPIView
from rest_framework.mixins import CreateModelMixin, UpdateModelMixin
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet

from users import constants
from users.serializers import UserSerializer, AddressTitleSerializer, AddressSerializer


class UserView(GenericAPIView):
    # 创建序列化器
    # 指定序列化器对象
    serializer_class = UserSerializer

    def post(self, request):
        # 获取信息并进行参数校验
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        # 保存数据
        serializer.save()

        return Response(serializer.data, status=status.HTTP_201_CREATED)


class AddressViewSet(CreateModelMixin, GenericViewSet):
    permission_classes = [IsAuthenticated]
    serializer_class = AddressSerializer
    # queryset = request.user.addresses.filter(is_deleted=False)

    def get_queryset(self):
        """返回视图所使用的查询集"""
        return self.request.user.addresses.filter(is_deleted=False)

    # POST /addresses/
    def create(self, request):
        """
        request.user：登录用户对象
        新增地址数据的保存:
        0. 判断用户的地址数量是否超过上限
        1. 获取参数并进行校验(参数完整性，手机号格式)
        2. 保存新增地址的数据
        3. 将新增地址的数据序列化并返回
        """
        # 0. 判断用户的地址数量是否超过上限
        count = request.user.addresses.filter(is_deleted=False).count()

        if count >= constants.USER_ADDRESS_COUNTS_LIMIT:
            return Response({'message': '地址数量超过最大上限'}, status=status.HTTP_403_FORBIDDEN)

        # 1. 获取参数并进行校验(参数完整性，手机号格式)
        # serializer = self.get_serializer(data=request.data)
        # serializer.is_valid(raise_exception=True)
        #
        # # 2. 保存新增地址的数据(create)
        # serializer.save()
        #
        # # 3. 将新增地址的数据序列化并返回
        # return Response(serializer.data, status=status.HTTP_201_CREATED)

        #调用`CreateModelMixin`中的create
        return super().create(request)

    # GET /addresses/
    def list(self, request):
        """
        获取用户的地址信息:
        1. 获取登录用户的地址的数据
        2. 将地址数据序列化
        3. 返回响应
        """
        # 1. 获取登录用户的地址的数据
        addresses = self.get_queryset()

        # 2. 将地址数据序列化
        serializer = self.get_serializer(addresses, many=True)

        # 3. 返回响应
        response_data = {
            'user_id': request.user.id,
            'default_address_id': request.user.default_address_id,
            'limit': constants.USER_ADDRESS_COUNTS_LIMIT,
            'addresses': serializer.data
        }
        return Response(response_data)

    # PUT /addresses/(?P<pk>\d+)/
    # def update(self, request, pk):
    #     """
    #     修改指定的用户的地址数据:
    #     1. 根据pk获取对应的地址
    #     2. 获取参数并进行校验(参数完整性，手机号)
    #     3. 修改的指定的地址数据
    #     4. 将修改地址数据序列化并返回
    #     """
    #     # 1. 获取对应的地址
    #     addr = self.get_object()
    #
    #     # 2. 获取参数并进行校验(参数完整性，手机号)
    #     serializer = self.get_serializer(addr, data=request.data)
    #     serializer.is_valid(raise_exception=True)
    #
    #     # 3. 修改的指定的地址数据(update)
    #     serializer.save()
    #
    #     # 4. 将修改地址数据序列化并返回
    #     return Response(serializer.data)

    # DELETE /address/(?P<pk>\d+)/
    def destroy(self, request, pk):
        """
        删除指定的地址数据:
        1. 根据pk获取指定的地址数据
        2. 将地址数据进行逻辑删除
        3. 返回应答，status=204
        """
        # 1. 根据pk获取指定的地址数据
        address = self.get_object()

        # 2. 将地址数据进行逻辑删除
        address.is_deleted = True
        address.save()

        # 3. 返回应答，status=204
        return Response(status=status.HTTP_204_NO_CONTENT)

    # PUT /adddresses/(?P<pk>\d+)/status/
    @action(methods=['put'], detail=True)
    def status(self, request, pk):
        """
        设置默认地址:
        1. 根据pk获取对应地址数据
        2. 将此地址设置为用户的默认地址
        3. 返回应答
        """
        # 1. 根据pk获取对应地址数据
        address = self.get_object()

        # 2. 将此地址设置为用户的默认地址
        # request.user.default_address = address
        request.user.default_address_id = address.id
        request.user.save()

        # 3. 返回应答
        return Response({'message': 'OK'})

    # PUT /adddresses/(?P<pk>\d+)/title/
    @action(methods=['put'], detail=True)
    def title(self, request, pk):
        """
        修改指定地址的标题:
        1. 根据pk获取指定的地址数据
        2. 获取title并校验
        3. 修改地址的title标题
        4. 返回应答
        """
        # 1. 根据pk获取指定的地址数据
        address = self.get_object()

        # 2. 获取title并校验
        serializer = AddressTitleSerializer(address, data=request.data)
        serializer.is_valid(raise_exception=True)

        # 3. 修改地址的title标题(update)
        serializer.save()

        # 4. 返回应答
        return Response(serializer.data)


